package com.lebang.service;

import com.lebang.component.RedisClient;
import com.lebang.component.RedisSdkClient;
import com.lebang.entity.MemberVideoCheck;
import com.lebang.mapper.LbbMemberRecordMapper;
import com.lebang.model.TaskInitModel;
import com.lebang.model.enums.buss.TaskCategory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.List;

import static com.lebang.controller.api.SdkUploadApi.CSJ;

/**
 * 任务的控制，redis 来控制
 *
 * @author Eliohn on 2019/9/2.
 * @version 1.0
 */
@Slf4j
@Service
public class TaskInRedisService {
    private static final String COLSE_HASH = "colse_task_key:";

    public static final String HASH_CSJ = "HASH_CSJ";

    // 任务被领取的记录，用来记录任务超时
    private static final String RECORD_TACK = "recordTask:";
    //任务超时时间
    private static final Integer EVENT_TIME = 1800;
    @Autowired
    private LbbMemberRecordMapper lbbMemberRecordMapper;
    private static final String TASK_RECORD_COUNT = "task_record_count";

    @Autowired
    private RedisClient redisClient;
    @Autowired
    private RedisSdkClient redisSdkClient;

    public static String getRecordTackPrefix() {
        return RECORD_TACK;
    }


    /**
     * 获取通用搜搜任务每日量
     */
    public Integer getTaskAmount(String key, String taskId) {
        //String amout = redisClient.hget(key, taskId);
        String amout = redisSdkClient.hget(key, taskId);
        if (amout == null) {
            return 0;
        }
        try {
            return Integer.parseInt(amout);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 删除任务记录
     *
     * @param recordId 记录ID
     */
    public void recordDel(Integer recordId) {
        redisClient.del(RECORD_TACK + recordId);
        //redisSdkClient.del(RECORD_TACK + recordId);
    }

    public void recordDel(Long recordId) {
        redisClient.del(RECORD_TACK + recordId);
    }

    /**
     * 设置任务过期监听事件
     */
    public void recordAdd(Integer i) {
        redisClient.setex(RECORD_TACK + i.toString(), EVENT_TIME, "1");
        //redisSdkClient.setex(RECORD_TACK + i.toString(), EVENT_TIME, "1");
    }
    /**
     * 设置任务过期监听事件
     */
    public void recordAdd(Integer i,Integer time) {
        redisClient.setex(RECORD_TACK + i.toString(), time*60, "1");
        //redisSdkClient.setex(RECORD_TACK + i.toString(), time*60, "1");
    }
    /**
     * 设置任务过期监听事件
     */
    public void recordAdd(Long i) {
        redisClient.setex(RECORD_TACK + i.toString(), EVENT_TIME, "1");
        //redisSdkClient.setex(RECORD_TACK + i.toString(), EVENT_TIME, "1");
    }

    /**
     * 通用搜搜任务每日量+1
     */
    public boolean taskAmountAdd(String key, String taskId) {
        //return redisClient.hincrBy(key, taskId, 1) > 0;
        return redisSdkClient.hincrBy(key, taskId, 1) > 0;
    }

    /**
     * 通用搜搜任务每日量-1
     */
    public boolean taskAmountSubtract(String key, String taskId) {
       // return redisClient.hincrBy(key, taskId, -1) > 0;
        return redisSdkClient.hincrBy(key, taskId, -1) > 0;
    }

    /**
     * 加载任务每日量方法
     */
    public boolean taskInitByTaskModelList(String taskKey, List<TaskInitModel> taskList, TaskCategory category, LocalDateTime dateTime) {

        try {
            taskList.forEach(task -> {
                int count;
                if (task.getTotal() == 0) {
                    task.setTotal(99999999);
                }
                if (task.getAmount() == 0) {
                    task.setAmount(9999);
                }
                if (task.getSuccessTotal() >= task.getTotal()) {
                    count = 0;
                } else {
                    if (task.getTotal() - task.getSuccessTotal() >= task.getAmount()) {
                        count = task.getAmount() ;
                    } else {
                        count = task.getTotal() - task.getSuccessTotal();
                    }
                }
                //获取全部待提交任务也计入每日量
                int o = lbbMemberRecordMapper.getWaitSubit(task.getTaskId());
                count = count - o;
                if (count < 0) {
                    count = 0;
                }
                //redisClient.hset(taskKey, task.getTaskId(), Integer.toString(count));
                redisSdkClient.hset(taskKey, task.getTaskId(), Integer.toString(count));
            });
            log.info("加载" + category.getTitle() + "每日量任务到redis中成功");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 加载单个任务
     *
     * @param taskKey
     * @param model
     * @return
     */
    public boolean taskInitByTaskModel(String taskKey, TaskInitModel model, LocalDateTime dateTime) {
        try {
            int count;
            if (model.getTotal() == 0) {
                model.setTotal(99999999);
            }
            if (model.getAmount() == 0) {
                model.setAmount(9999);
            }
            if (model.getSuccessTotal() >= model.getTotal()) {
                count = 0;
            } else {
                if (model.getTotal() - model.getSuccessTotal() >= model.getAmount()) {
                    count = model.getAmount() ;
                } else {
                    count = model.getTotal() - model.getSuccessTotal();
                }
            }
            //获取当日待提交任务也计入每日量
            int o = lbbMemberRecordMapper.getWaitSubit(model.getTaskId());
            count = count - o;
            if (count < 0) {
                count = 0;
            }
            //redisClient.hset(taskKey, model.getTaskId(), Integer.toString(count));
            redisSdkClient.hset(taskKey, model.getTaskId(), Integer.toString(count));
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 穿山甲视频回调后记录redis当日次数 用于验证用户每次看视频的等待时间
     *
     * @param memberId
     */
    public void csjAdd(String memberId, List<MemberVideoCheck> videoChecks) {
        try {

            Integer count = 0;
            Object obj = redisClient.hget(HASH_CSJ, memberId);
            if (obj != null) {
                count = Integer.parseInt(obj.toString());
                redisClient.hincrby(HASH_CSJ, memberId, 1L);
            } else {
                redisClient.hset(HASH_CSJ, memberId, "1");
            }
            count = count + 1;

            for (Iterator<MemberVideoCheck> iterator = videoChecks.iterator(); iterator.hasNext(); ) {
                MemberVideoCheck next = iterator.next();
                if (count > next.getCount()) {
                    redisClient.setex(CSJ + memberId, count.toString(), next.getSeconds());
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static final String REDBOOK_FITER = "REDBOOK_FITER:";

    /**
     * 增加小红书的过滤 完成过小红书任务后调用 用户在lessTime小时内看不见小红书任务 也不能领取小红书任务
     *
     * @param memberId
     * @param lessTime
     */
    public void addRedBookFiter(String memberId, Integer lessTime) {
        //redisClient.setex(REDBOOK_FITER + memberId, memberId, lessTime * 3600);
        redisSdkClient.setex(REDBOOK_FITER + memberId, memberId, lessTime * 3600);
    }

    /**
     * 解除用户小红书的过滤 解除后可以正常访问
     *
     * @param memberId
     */
    public void cleanRedBookFiter(String memberId) {
        //redisClient.del(REDBOOK_FITER + memberId);
        redisSdkClient.del(REDBOOK_FITER + memberId);
    }

    /**
     * 验证用户是否开启了小红书的过滤
     *
     * @param memberId
     * @return
     */
    public boolean checkRedBookFiter(String memberId) {
        //return redisClient.exists(REDBOOK_FITER + memberId);
        return redisSdkClient.exists(REDBOOK_FITER + memberId);
    }

    /**
     * 验证小红书一级过滤
     *
     * @param taskid
     * @return
     */
    public boolean checkRedBookByTaksId(String taskid) {
        //return redisClient.exists(COLSE_HASH + taskid);
        return redisSdkClient.exists(COLSE_HASH + taskid);
    }

    /**
     * 增加小红书一级过滤
     *
     * @param taskid  任务id
     * @param seconds 分钟
     * @return
     */
    public void addCheckRedBookByTaksId(String taskid, Integer seconds) {
        //增加一个key控制任务隐藏
        //redisClient.setex(COLSE_HASH + taskid, taskid, seconds * 60);
        redisSdkClient.setex(COLSE_HASH + taskid, taskid, seconds * 60);
        //删除领取数量
        //redisClient.hdel(TASK_RECORD_COUNT, taskid);
        redisSdkClient.hdel(TASK_RECORD_COUNT, taskid);
    }

    /**
     * 任务领取数量+1
     *
     * @param taskId
     */
    public long recordAddRedBook(String taskId) {
        //return redisClient.hincrBy(TASK_RECORD_COUNT, taskId, 1);
        return redisSdkClient.hincrBy(TASK_RECORD_COUNT, taskId, 1);
    }
}
